$(document).ready(function() {
    
    // 用于跟踪已经增加浏览量的图片ID，避免重复调用
    var viewCountIncremented = new Set();
    
    // 获取初始选中的图片信息
    updateCurrentImageInfo();
    
    // 为所有主图片添加load事件监听器
    addImageLoadListeners();
    
    // 缩略图轮播初始化（只有多张图片时才初始化）
    var thumbsSwiper = null;
    if (images.length > 1) {
        thumbsSwiper = new Swiper(".thumbnail-swiper", {
            spaceBetween: 10,
            slidesPerView: isMobile ? 3 : 4,
            freeMode: true,
            watchSlidesProgress: true,
            breakpoints: {
                640: {
                    slidesPerView: isMobile ? 4 : 4,
                },
                768: {
                    slidesPerView: isMobile ? 5 : 4,
                }
            }
        });
    }
    
    // 主轮播图初始化
    if (images.length > 1) {
        var mainSwiper = new Swiper(".main-swiper", {
            spaceBetween: 10,
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
            // 只有当存在缩略图轮播时才设置thumbs
            thumbs: images.length > 1 ? {
                swiper: thumbsSwiper,
            } : undefined,
            on: {
                slideChangeTransitionEnd: function() {
                    // 当轮播图切换完成后停止之前播放的视频
                    stopAllVideos();
                    // 当轮播图切换完成后更新当前图片信息
                    updateCurrentImageInfo();
                    // 为新的活动slide添加图片加载监听器
                    addImageLoadListeners();
                }
            }
        });
    }
    
    // 下载按钮点击事件
    $("#download-btn").click(function() {
        showDownloadModal();
    });
    
    // 收藏按钮点击事件
    $("#favorite-btn").click(function() {
        toggleFavorite();
    });
    
    // 播放按钮点击事件
    $(".play-button").click(function(e) {
        e.preventDefault();
        var slide = $(this).closest('.swiper-slide');
        var video = slide.find('video');
        var image = slide.find('img[data-video-poster]');
        
        // 停止其他可能正在播放的视频
        stopAllVideos();
        
        // 隐藏图片，显示视频
        image.addClass('hidden');
        video.removeClass('hidden');
        $(this).addClass('hidden');
        
        // 播放视频
        video[0].play();
        currentVideoPlaying = video[0];
        
        // 添加视频结束事件
        video.on('ended', function() {
            // 视频播放结束后，隐藏视频，显示图片和播放按钮
            video.addClass('hidden');
            image.removeClass('hidden');
            slide.find('.play-button').removeClass('hidden');
            currentVideoPlaying = null;
        });
    });

    // 停止所有视频播放
    function stopAllVideos() {
        if (currentVideoPlaying) {
            currentVideoPlaying.pause();
            currentVideoPlaying.currentTime = 0;
            
            // 隐藏视频，显示图片和播放按钮
            var slide = $(currentVideoPlaying).closest('.swiper-slide');
            $(currentVideoPlaying).addClass('hidden');
            slide.find('img[data-video-poster]').removeClass('hidden');
            slide.find('.play-button').removeClass('hidden');
            
            currentVideoPlaying = null;
        }
    }
    
    // 更新当前图片信息
    function updateCurrentImageInfo() {
        // 获取当前活动slide的索引
        var activeIndex = $('.main-swiper .swiper-slide-active').index();
        
        // 初始调用时可能是-1，这时使用第一张图片
        if (activeIndex < 0 && images.length > 0) {
            activeIndex = 0;
        }
        
        // 确保索引有效
        if (activeIndex >= 0 && activeIndex < images.length) {
            // 从images数组中获取当前图片数据
            currentImage = images[activeIndex];
            
            // 更新当前文件路径和描述
            currentFilePath = currentImage.file_path;
            currentDescription = currentImage.description;
            
            // 更新图片描述
            if (currentDescription) {
                $("#current-image-description").text(currentDescription);
                $("#image-description-container").removeClass('hidden');
            } else {
                $("#image-description-container").addClass('hidden');
            }
            $('#current-view-count').text(currentImage.view_cnt);
            $('#current-download-count').text(currentImage.download_cnt);
            $('#current-update-time').text(currentImage.update_time);
            
            
            
            
            
            console.log("当前图片索引:", activeIndex, "文件路径:", currentFilePath, "图片信息:", currentImage);
        }
    }
    
    // 显示下载弹层
    function showDownloadModal() {
        // 创建弹层HTML
        if ($('#download-modal-overlay').length === 0) {
            var themeClass = '';
            if (wallpaperType == 'desktop') {
                themeClass = 'desktop';
            } else if (wallpaperType == 'mobile') {
                themeClass = 'mobile';
            } else if (wallpaperType == 'dynamic_desktop') {
                themeClass = 'desktop';
            } else {
                themeClass = 'mobile';
            }
            
            var modalHtml = `
                <div id="download-modal-overlay" class="modal-overlay">
                    <div class="download-modal">
                        <div class="relative">
                            <h3 class="text-xl font-bold text-${getColorClass()} mb-4">選擇下載分辨率</h3>
                            <div id="download-options-container"></div>
                            <div id="modal-description" class="image-description text-sm"></div>
                            <div class="close-modal">&times;</div>
                        </div>
                    </div>
                </div>
            `;
            
            $('body').append(modalHtml);
            
            // 关闭弹层事件
            $(document).on('click', '.close-modal, .modal-overlay', function(e) {
                if (e.target === this) {
                    $('#download-modal-overlay').removeClass('active');
                }
            });
        }
        
        // 解析文件路径JSON
        try {
            // 检查currentFilePath是否为空
            if (!currentFilePath) {
                throw new Error('文件路径为空');
            }
            
            var filePaths = JSON.parse(currentFilePath);
            var optionsHtml = '';
            var themeClass = getThemeClass();
            
            // 生成下载选项
            if (filePaths['640'] && filePaths['640'] !== '') {
                optionsHtml += createDownloadOption('640', '640px', filePaths['640'], themeClass);
            }
            
            if (filePaths['1k'] && filePaths['1k'] !== '') {
                optionsHtml += createDownloadOption('1k', '1920×1080', filePaths['1k'], themeClass);
            }
            
            if (filePaths['2k'] && filePaths['2k'] !== '') {
                optionsHtml += createDownloadOption('2k', '2560×1440', filePaths['2k'], themeClass);
            }
            
            if (filePaths['4k'] && filePaths['4k'] !== '') {
                optionsHtml += createDownloadOption('4k', '3840×2160', filePaths['4k'], themeClass);
            }
            if (filePaths['mp4'] && filePaths['mp4'] !== '') {
                optionsHtml += createDownloadOption('mp4', 'MP4格式', filePaths['mp4'], themeClass);
            }
            
            // 如果没有选项，显示提示
            if (optionsHtml === '') {
                optionsHtml = '<p class="text-center text-gray-500 py-4">暫無可下載的分辨率選項</p>';
            }
            
            // 更新弹层内容
            $('#download-options-container').html(optionsHtml);
            
            // 设置描述
            if (currentDescription) {
                $('#modal-description').text(currentDescription).show();
            } else {
                $('#modal-description').hide();
            }
            
            // 显示弹层
            $('#download-modal-overlay').addClass('active');
            
        } catch (e) {
            console.error('解析文件路径失败:', e);
        }
    }
    
    // 下载按钮点击事件监听
    $(document).on('click', '.download-option-btn', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var downloadUrl = $btn.data('url');
        var resolution = $btn.data('resolution');
        
        // 防止重复点击
        if ($btn.prop('disabled')) {
            return;
        }
        
        $btn.prop('disabled', true);
        var originalText = $btn.html();
        $btn.html('<i class="fas fa-spinner fa-spin mr-1"></i>下載中...');
        
        // 调用 /user/addAction 接口记录下载行为
        $.ajax({
            url: '/user/addAction',
            type: 'POST',
            data: {
                image_id: currentImage.id,
                action_type: 'download'
            },
            dataType: 'json',
            success: function(response) {
                if (response.code === 200) {
                    // 记录成功，触发实际下载
                    triggerDownload(downloadUrl, resolution);
                    showMessage('下載記錄已保存', 'success');
                    
                    // 关闭弹层
                    setTimeout(function() {
                        $('#download-modal-overlay').removeClass('active');
                    }, 1000);
                } else {
                    showMessage(response.msg || '下載記錄保存失敗', 'error');
                }
            },
            error: function() {
                // 即使记录失败，也允许下载
                triggerDownload(downloadUrl, resolution);
                showMessage('下載記錄保存失敗，但文件下載已開始', 'warning');
                
                // 关闭弹层
                setTimeout(function() {
                    $('#download-modal-overlay').removeClass('active');
                }, 1000);
            },
            complete: function() {
                $btn.prop('disabled', false);
                $btn.html(originalText);
            }
        });
    });
    
    // 触发文件下载
    function triggerDownload(url, resolution) {
        // 创建隐藏的下载链接
        var link = document.createElement('a');
        link.href = url;
        link.download = '';
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    
    // 创建下载选项HTML
    function createDownloadOption(key, resolution, path, themeClass) {
        var displayText = {
            '640': '小尺寸',
            '1k': '1080P高清',
            '2k': '2K超清',
            '4k': '4K超高清',
            'mp4': 'MP4格式'
        };
        
        var fullUrl = path.startsWith('http') ? path : att_domain + path;
        
        return `
            <div class="download-option flex justify-between items-center">
                <div>
                    <div class="font-bold">${displayText[key] || key}</div>
                    <div class="text-sm text-gray-500">${resolution}</div>
                </div>
                <button class="download-option-btn ${themeClass}" data-url="${fullUrl}" data-resolution="${key}">
                    下載 <i class="fas fa-arrow-down ml-1"></i>
                </button>
            </div>
        `;
    }

    function getThemeClass() {
        if (wallpaperType == 'desktop') {
            return 'desktop';
        } else if (wallpaperType == 'mobile') {
            return 'mobile';
        } else if (wallpaperType == 'dynamic_desktop') {
            return 'desktop';
        } else {
            return 'mobile';
        }
    }

    function getColorClass() {
        if (wallpaperType == 'desktop') {
            return 'primary';
        } else if (wallpaperType == 'mobile') {
            return 'accent';
        } else if (wallpaperType == 'dynamic_desktop') {
            return 'blue-500';
        } else {
            return 'yellow-600';
        }
    }
    
    // 切换收藏状态
    function toggleFavorite() {
        var $btn = $('#favorite-btn');
        var isFavorited = $btn.hasClass('favorited');
        
        // 防止重复点击
        if ($btn.prop('disabled')) {
            return;
        }
        
        $btn.prop('disabled', true);
        
        var url = isFavorited ? '/user/removeAction' : '/user/addAction';
        
        $.ajax({
            url: url,
            type: 'POST',
            data: {
                image_id: currentImage.id,
                action_type: 'like'
            },
            dataType: 'json',
            success: function(response) {
                if (response.code === 200) {
                    updateFavoriteButton(!isFavorited);
                    // 显示成功提示
                    showMessage(isFavorited ? '已取消收藏' : '已加入收藏', 'success');
                } else {
                    showMessage(response.msg || '操作失败', 'error');
                }
            },
            error: function() {
                showMessage('网络错误，请稍后重试', 'error');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    }
    
    // 更新收藏按钮状态
    function updateFavoriteButton(isFavorited) {
        var $btn = $('#favorite-btn');
        var $text = $('#favorite-text');
        var $icon = $btn.find('i');
        
        if (isFavorited) {
            $btn.addClass('favorited');
            $text.text('已收藏');
            $icon.removeClass('far').addClass('fas');
        } else {
            $btn.removeClass('favorited');
            $text.text('加入收藏');
            $icon.removeClass('fas').addClass('far');
        }
    }
    
    // 显示消息提示
    function showMessage(message, type) {
        var bgColor = type === 'success' ? 'bg-green-500' : (type === 'warning' ? 'bg-yellow-500' : 'bg-red-500');
        var messageHtml = `
            <div id="message-toast" class="fixed top-4 right-4 ${bgColor} text-white px-4 py-2 rounded-md shadow-lg z-50 transition-all duration-300 transform translate-x-full">
                ${message}
            </div>
        `;
        
        // 移除已存在的消息
        $('#message-toast').remove();
        
        // 添加新消息
        $('body').append(messageHtml);
        
        // 显示动画
        setTimeout(function() {
            $('#message-toast').removeClass('translate-x-full');
        }, 100);
        
        // 3秒后自动隐藏
        setTimeout(function() {
            $('#message-toast').addClass('translate-x-full');
            setTimeout(function() {
                $('#message-toast').remove();
            }, 300);
        }, 3000);
    }

    // 为图片添加load事件监听器的函数
    function addImageLoadListeners() {
        // 获取当前活动的slide
        var activeIndex = $('.main-swiper .swiper-slide-active').index();
        
        // 初始调用时可能是-1，这时使用第一张图片
        if (activeIndex < 0 && images.length > 0) {
            activeIndex = 0;
        }
        
        // 确保索引有效
        if (activeIndex >= 0 && activeIndex < images.length) {
            // 从images数组中获取当前图片数据
            let img = $('.swiper-slide img').eq(activeIndex);
            let imageId = getCurrentImageId();
            // 检查图片是否已经加载完成
            if (img[0].complete && img[0].naturalHeight !== 0) {
                // 图片已经加载完成，直接调用增加浏览量
                incrementViewCount(imageId);
            } else {
                // 图片还未加载完成，添加load事件监听器
                img.off('load.viewcount').on('load.viewcount', function() {
                    incrementViewCount(imageId);
                });
                
                // 添加错误处理
                img.off('error.viewcount').on('error.viewcount', function() {
                    console.log('图片加载失败，但仍然增加浏览量');
                    incrementViewCount(imageId);
                });
            }
        }
    }
    
    // 获取当前图片ID的函数
    function getCurrentImageId() {
        var activeIndex = $('.main-swiper .swiper-slide-active').index();
        if (activeIndex < 0 && images.length > 0) {
            activeIndex = 0;
        }
        
        if (activeIndex >= 0 && activeIndex < images.length) {
            return images[activeIndex].id;
        }
        
        // 如果无法从images数组获取，尝试从全局变量获取
        return typeof wallpaperId !== 'undefined' ? wallpaperId : null;
    }
    
    // 增加浏览量的AJAX函数
    function incrementViewCount(imageId) {
        // 检查是否已经为这个图片增加过浏览量
        if (!imageId || viewCountIncremented.has(imageId)) {
            return;
        }
        
        // 标记这个图片已经增加过浏览量
        viewCountIncremented.add(imageId);
        
        // 发送AJAX请求增加浏览量
        $.ajax({
            url: '/index/increment_view_cnt',
            type: 'POST',
            data: {
                id: imageId
            },
            success: function(response) {
                console.log('浏览量增加成功');
                
               
            },
            error: function(xhr, status, error) {
                console.log('浏览量增加请求失败:', error);
            }
        });
    }
    
});